package com.zsc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zsc.constant.MessageConstant;
import com.zsc.context.BaseContext;
import com.zsc.dto.OrdersPageQueryDTO;
import com.zsc.dto.OrdersSubmitDTO;
import com.zsc.entity.AddressBook;
import com.zsc.entity.OrderDetail;
import com.zsc.entity.Orders;
import com.zsc.entity.ShoppingCart;
import com.zsc.exception.AddressBookBusinessException;
import com.zsc.mapper.OrdersMapper;
import com.zsc.result.PageResult;
import com.zsc.service.AddressBookService;
import com.zsc.service.OrderDetailService;
import com.zsc.service.OrdersService;
import com.zsc.service.ShoppingCartService;
import com.zsc.utils.CopyUtil;
import com.zsc.vo.OrderDetailVO;
import com.zsc.vo.OrderSearchVO;
import com.zsc.vo.OrderSubmitVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;


/**
 * @author cjr165123050
 * @description 针对表【orders(订单表)】的数据库操作Service实现
 * @createDate 2024-05-19 11:13:32
 */
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {

    @Autowired
    private OrderDetailService orderDetailService;


    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private ShoppingCartService shoppingCartService;


    /**
     * 管理端 订单分页查询
     *
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(OrdersPageQueryDTO ordersPageQueryDTO) {
        Page<Orders> ordersPage = new Page<>(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());

        LambdaQueryWrapper<Orders> ordersLambdaQueryWrapper = new LambdaQueryWrapper<>();

        ordersLambdaQueryWrapper.eq(!StringUtils.isBlank(ordersPageQueryDTO.getNumber()),
                        Orders::getPhone, ordersPageQueryDTO.getPhone())
                .eq(Objects.nonNull(ordersPageQueryDTO.getStatus()),
                        Orders::getStatus, ordersPageQueryDTO.getStatus())
                .eq(StringUtils.isBlank(ordersPageQueryDTO.getNumber()),
                        Orders::getNumber, ordersPageQueryDTO.getNumber());

        //判断时间
        ordersLambdaQueryWrapper.ge(ordersPageQueryDTO.getBeginTime() != null,
                Orders::getOrderTime, ordersPageQueryDTO.getBeginTime());

        ordersLambdaQueryWrapper.le(ordersPageQueryDTO.getEndTime() != null,
                Orders::getOrderTime, ordersPageQueryDTO.getEndTime());

        Page<Orders> page = this.page(ordersPage, ordersLambdaQueryWrapper);

        List<Orders> records = page.getRecords();

        List<OrderDetail> list = orderDetailService.list();

        ArrayList<OrderSearchVO> orderVOS = new ArrayList<>();
        for (Orders record : records) {

            List<OrderDetail> collect = list.stream()
                    .filter(it -> it.getOrderId().equals(record.getId()))
                    .collect(Collectors.toList());

            List<String> list1 = collect.stream()
                    .map(orderDetail -> orderDetail.getName() + "*" + orderDetail.getNumber())
                    .collect(Collectors.toList());

            String join = String.join(",", list1);
            OrderSearchVO copy = CopyUtil.copy(record, OrderSearchVO.class);
            copy.setOrderDishes(join);
            orderVOS.add(copy);
        }

        return new PageResult(page.getTotal(), orderVOS);
    }


    /**
     * 用户端 历史订单分页查询
     *
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult historyOrderPageQuery(OrdersPageQueryDTO ordersPageQueryDTO) {

        // 创建分页对象
        Page<Orders> ordersPage = new Page<>(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        // 构建查询条件
        QueryWrapper<Orders> queryWrapper = new QueryWrapper<>();
        if (ordersPageQueryDTO.getStatus() != null) {
            queryWrapper.eq("status", ordersPageQueryDTO.getStatus());
        }
        if (ordersPageQueryDTO.getPhone() != null) {
            queryWrapper.eq("phone", ordersPageQueryDTO.getPhone());
        }
        if (ordersPageQueryDTO.getBeginTime() != null) {
            queryWrapper.ge("order_time", ordersPageQueryDTO.getBeginTime());
        }
        if (ordersPageQueryDTO.getEndTime() != null) {
            queryWrapper.le("order_time", ordersPageQueryDTO.getEndTime());
        }

        queryWrapper.eq("user_id", BaseContext.getCurrentId()); // 添加查询条件：user_id等于当前登录用户的ID
        // 执行分页查询
        Page<Orders> result = this.page(ordersPage, queryWrapper);

        // 将查询结果转换为OrderDetailVO列表
        List<OrderDetailVO> orderDetailVOList = new ArrayList<>();
        for (Orders order : result.getRecords()) {
            OrderDetailVO orderDetailVO = CopyUtil.copy(order, OrderDetailVO.class);
            BeanUtils.copyProperties(order, orderDetailVO);

            // 查询OrderDetail表的内容并添加到orderDetailList中
            QueryWrapper<OrderDetail> orderDetailWrapper = new QueryWrapper<>();
            orderDetailWrapper.eq("order_id", order.getId());
            List<OrderDetail> orderDetailList = orderDetailService.list(orderDetailWrapper);

            orderDetailVO.setOrderDishes(orderDetailList.stream().map(OrderDetail::getName).collect(Collectors.joining(",")));

            orderDetailVO.setOrderDetailList(orderDetailList);
            orderDetailVOList.add(orderDetailVO);
        }

        // 创建PageResult对象并返回
        return new PageResult(result.getTotal(), orderDetailVOList);
    }


    /**
     * 用户端 查询订单详情
     *
     * @param id
     * @return
     */

    @Override
    public OrderDetailVO OrderDetail(Long id) {
        QueryWrapper<Orders> orderWrapper = new QueryWrapper<>();
        // 根据id和user_id查询
        orderWrapper.eq("id", id).eq("user_id", BaseContext.getCurrentId());
        Orders orders = this.getOne(orderWrapper);
        OrderDetailVO orderDetailVO = CopyUtil.copy(orders, OrderDetailVO.class);
        BeanUtils.copyProperties(orders, orderDetailVO);

        AddressBook addressBook = addressBookService.getById(orders.getAddressBookId());
        String address = addressBook.getProvinceName()
                + addressBook.getCityName()
                + addressBook.getDistrictName()
                + addressBook.getDetail();
        orderDetailVO.setAddress(address);

        // 查询OrderDetail表的内容并添加到orderDetailList中
        QueryWrapper<OrderDetail> orderDetailWrapper = new QueryWrapper<>();
        orderDetailWrapper.eq("order_id", id);
        List<OrderDetail> orderDetailList = orderDetailService.list(orderDetailWrapper);
        orderDetailVO.setOrderDetailList(orderDetailList);

        // 订单包含的菜品 用逗号分隔（本来最好用列表存储）
        // private String orderDishes;
        orderDetailVO.setOrderDishes(orderDetailList.stream().map(OrderDetail::getName).collect(Collectors.joining(",")));


        return orderDetailVO;
    }

    /**
     * 用户端 再来一单
     *
     * @param id
     */
    @Override
    public void repeatOrder(Long id) {
        // 根据订单ID查找原始订单
        QueryWrapper<Orders> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id).eq("user_id", BaseContext.getCurrentId());
        Orders originalOrder = getOne(queryWrapper);

        if (originalOrder == null) {
            throw new RuntimeException("订单不存在");
        }

        // 复制原始订单的信息到新订单对象中
        Orders newOrder = new Orders();
        BeanUtils.copyProperties(originalOrder, newOrder);

        // 重置新订单的ID和创建时间，并设置状态为未完成
        newOrder.setNumber(String.valueOf(System.currentTimeMillis()));
        newOrder.setId(null); // 重置ID以便生成新的ID
        newOrder.setOrderTime(LocalDateTime.now()); // 重置创建时间
        newOrder.setStatus(0); // 设置状态为未完成

        // 保存新订单到数据库
        save(newOrder);
        List<OrderDetail> orderDetailList = orderDetailService.list(new QueryWrapper<OrderDetail>().eq("order_id", id));
        orderDetailList.forEach(orderDetail -> {
            orderDetail.setId(null);
            orderDetail.setOrderId(newOrder.getId());
            orderDetailService.save(orderDetail);
        });
        BaseContext.removeCurrentId();
        BaseContext.setCurrentId(originalOrder.getUserId());
    }

    /**
     * 提交购物车生成订单
     *
     * @param ordersSubmitDTO
     * @return
     */
    @Override
    @Transactional
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {
        // 处理业务异常（地址簿为空，购物车数据为空）
//        AddressBook addressBook = addressBookMapper.selectById(ordersSubmitDTO.getAddressBookId());
        AddressBook addressBook = addressBookService.getById(ordersSubmitDTO.getAddressBookId());

        if (addressBook == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        Long userId = BaseContext.getCurrentId();
        QueryWrapper<ShoppingCart> cartQueryWrapper = new QueryWrapper<>();
        cartQueryWrapper.eq("user_id", userId);
//        List<ShoppingCart> shoppingCartList = shoppingCartMapper.selectList(cartQueryWrapper);
        List<ShoppingCart> shoppingCartList = shoppingCartService.list(cartQueryWrapper);


        if (shoppingCartList == null || shoppingCartList.isEmpty()) {
            throw new AddressBookBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        // 向订单表插入一条数据
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        orders.setOrderTime(LocalDateTime.now());
        orders.setStatus(Orders.UNCOMPLETED);
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setPhone(addressBook.getPhone());
        orders.setConsignee(addressBook.getConsignee());
        orders.setUserId(userId);
        this.save(orders);
//        System.out.println(orders.getId());
        // 向订单详情表插入多条数据
        List<OrderDetail> orderDetailList = new ArrayList<>();
        for (ShoppingCart cart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();    // 订单明细
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetail.setId(null);
            orderDetail.setOrderId(orders.getId()); // 设置订单明细关联的订单id
            orderDetailList.add(orderDetail);
        }
//        orderDetailMapper.insertBatch(orderDetailList);
        orderDetailService.saveBatch(orderDetailList); // 批量插入订单详情
        // 清空用户购物车数据
//        shoppingCartMapper.delete(cartQueryWrapper);
        shoppingCartService.remove(cartQueryWrapper);
        // 封装VO返回结果
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(orders.getId())
                .orderTime(orders.getOrderTime())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .build();
        return orderSubmitVO;
    }

    @Override
    public OrderDetailVO OrderDetails(Long id) {
        Orders order = this.getById(id);
        LambdaQueryWrapper<OrderDetail> orderDetailLambdaQueryWrapper = new LambdaQueryWrapper<>();
        orderDetailLambdaQueryWrapper.eq(OrderDetail::getOrderId, order.getId());
        List<OrderDetail> list = orderDetailService.list(orderDetailLambdaQueryWrapper);
        OrderDetailVO orderDetailVO = CopyUtil.copy(order, OrderDetailVO.class);
        List<String> list1 = list.stream()
                .map(orderDetail -> orderDetail.getName() + "*" + orderDetail.getNumber())
                .collect(Collectors.toList());

        String join = String.join(",", list1);
        orderDetailVO.setOrderDishes(join);
        orderDetailVO.setOrderDetailList(list);
        return orderDetailVO;
    }
}
